from typing import List

from sqlalchemy import select, delete, and_
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.functions.user import get_user
from app.database.models import Document, User


async def add_document(
    session: AsyncSession, telegram_id: int, fullname: str, city: str
) -> None:

    user = await get_user(session, telegram_id)
    document = Document(
        user=user,
        fullname=fullname,
        city=city,
    )
    session.add(document)

    await session.commit()


async def get_user_docs(session: AsyncSession, user_id: int) -> List[Document]:
    q = select(Document).outerjoin(Document.user).where(User.telegram_id == user_id)

    res = await session.execute(q)

    return res.scalars().all()


async def delete_user_docs(session: AsyncSession, user_id: int) -> None:

    user = await get_user(session, user_id, joined=True)

    q = delete(Document).where(and_(Document.user == user, Document.status != "busy"))

    await session.execute(q)
    await session.commit()
